﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;

namespace Away.Common.Repository;

/// <summary>
/// 初始化创建表
/// </summary>
/// <typeparam name="TContext"></typeparam>
/// <param name="serviceProvider"></param>
public class InitTablesHostService<TContext>(IServiceProvider serviceProvider) : IHostedService where TContext : DbContext
{
    private readonly IServiceProvider _provider = serviceProvider;

    public async Task StartAsync(CancellationToken cancellationToken)
    {
        using var scope = _provider.CreateScope();
        var dbcontext = scope.ServiceProvider.GetRequiredService<TContext>();
        var sql = dbcontext.Database.GenerateCreateScript();
        try
        {
            await dbcontext.Database.GetDbConnection().OpenAsync(cancellationToken);
            using var cmd = dbcontext.Database.GetDbConnection().CreateCommand();
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
        }
        catch (Exception)
        {

        }
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}
